import { searchCover, isString, isNumber, isArray, safeGet, guID } from "@/common.js"
// 调整字段值
export const changeField = function (e, field) {
  e = e || ''
  const value = isString(e) || isNumber(e) || isArray(e) ? e : e.target.value
  // 更新右侧的值
  const item = {...this.item, [field]: value}
  this.$emit('setItem', item)
  // 更新整体表单的值
  let formData = searchCover(this.formData, {id: this.item.id}, v => ({...v, [field]: value}))
  formData = formData.map(v => ({...v, children: v.type == 'split' ? searchCover(v.children, {id: this.item.id}, v => ({...v, [field]: value})) : v.children}))
  this.$emit('setFormData', formData)
}
// 添加药物
export const addItem = function () {
  const tableData = [...this.tableData, { id: guID(),name: '', useage: '', useageOther: '', frequency: '',frequencyOther: '', dosage: '', dosageUnit:'', dosageUniteOther: '',time:'', timeUnit: '',}]
  this.changeField(JSON.stringify(tableData), 'value')
}
// 删除全部
export const delAll = function () {
  this.$zConfirm({
    title: '温馨提示',
    content: '确定要删除吗?',
    onOk: async () => {
      const tableData = []
      this.changeField(JSON.stringify(tableData), 'value')
    },
    onCancel: () => { }
  })
}
// 调整字段
export const changeForm = function (e, field, row) {
  const value = isString(e) || isNumber(e) || isArray(e) ? e : e.target.value
  const tableData = searchCover(this.tableData, {id: row.id}, v => ({...v, [field]: value}))
  this.changeField(JSON.stringify(tableData), 'value')
}
// 删除单个条目
export const delMedicine = function (row) {
  this.$zConfirm({
    title: '温馨提示',
    content: '确定要删除吗?',
    onOk: async () => {
      const tableData = this.tableData.filter(v => v.id !== row.id)
      this.changeField(JSON.stringify(tableData), 'value')
    },
    onCancel: () => { }
  })
}